package com.cyp.blogsystem.service.impl;

import com.cyp.blogsystem.exception.BusinessException;
import com.cyp.blogsystem.model.vo.UploadVO;
import com.cyp.blogsystem.service.OssService;
import com.cyp.blogsystem.service.UploadService;
import org.springframework.stereotype.Service;
import lombok.RequiredArgsConstructor;
import org.springframework.web.multipart.MultipartFile;

@Service
@RequiredArgsConstructor
public class UploadServiceImpl implements UploadService {

  private final OssService ossService;

  @Override
  public UploadVO uploadImage(MultipartFile file, String type) {
    // 1. 文件校验
    // 1.1 检查文件类型
    String contentType = file.getContentType();
    if (!isImageFile(contentType)) {
      throw new BusinessException("只支持上传图片文件");
    }

    // 1.2 检查文件大小
    if (file.getSize() > 10 * 1024 * 1024) {
      throw new BusinessException("图片大小不能超过10MB");
    }

    // 2. 上传文件到OSS
    String url = ossService.uploadFile(file, type);

    // 3. 构建返回结果
    UploadVO vo = new UploadVO();
    vo.setUrl(url);
    vo.setFilename(file.getOriginalFilename());
    vo.setSize(file.getSize());
    vo.setType(contentType);

    // 4. 返回上传结果
    return vo;
  }

  private boolean isImageFile(String contentType) {
    return contentType != null && contentType.startsWith("image/");
  }
}